package com.zhicheng.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConstants;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.zhicheng.exception.BaseException;
import com.zhicheng.mapper.OrderMapper;
import com.zhicheng.pojo.Order;
import com.zhicheng.properties.AlipayProperties;
import com.zhicheng.service.AliPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;


@Service
public class AliPayServiceImpl implements AliPayService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AlipayClient alipayClient;
    @Autowired
    private AlipayProperties alipayProperties;

    @Override
    public String tradeCreate(String orderId) {

        try {
            // 查询订单信息
            Order order = orderMapper.getByOrderId(orderId);

            // 调用支付宝接口
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
            //异步接收地址，仅支持http/https，公网可访问
            request.setNotifyUrl(alipayProperties.getNotifyUrl());
            //同步跳转地址，仅支持http/https
            request.setReturnUrl(alipayProperties.getReturnUrl());
            /******必传参数******/
            JSONObject bizContent = new JSONObject();
            //商户订单号，商家自定义，保持唯一性
            bizContent.put("out_trade_no", order.getId());
            //支付金额，最小值0.01元
            bizContent.put("total_amount", order.getPayAmount());
            //订单标题，不可使用特殊符号
            bizContent.put("subject", "志诚二手交易平台订单");
            //电脑网站支付场景固定传值FAST_INSTANT_TRADE_PAY
            bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
            //填充业务参数
            request.setBizContent(bizContent.toString());

            // 执行请求，调用支付宝接口
            AlipayTradePagePayResponse response = alipayClient.pageExecute(request, "GET");
            if (response.isSuccess()) {
                // 调用成功，则获取表单
                System.out.println("调用成功");
                String pageRedirectionData = response.getBody();
                System.out.println(pageRedirectionData);
                return response.getBody();// 此处返回的是表单HTML，需要直接输出到浏览器中
            } else {
                // 调用失败，则处理异常
                System.out.println("调用失败");
            }
        } catch (AlipayApiException e) {
            throw new BaseException("创建支付交易失败");
        }
        return null;
    }

    @Override
    public String tradeNotify(HttpServletRequest request) throws Exception {

        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
            }

            String sign = params.get("sign");
            String content = AlipaySignature.getSignCheckContentV1(params);
            String charset = AlipayConstants.CHARSET_UTF8;
            boolean signVerified = AlipaySignature.rsa256CheckContent(content, sign, alipayProperties.getPublicKey(), charset);  //调用SDK验证签名
            if (!signVerified) {
                // 验签失败
                System.out.println("支付成功异步通知验签失败！");
                return "failure";
            }else {
                // 验签通过
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));

                String tradeNo = params.get("out_trade_no");//订单编号
                String gmtPayment = params.get("gmt_payment");//支付时间
                String alipayTradeNo = params.get("trade_no");//支付宝交易编号
                // 更新订单已支付的逻辑代码
                Order order = orderMapper.getByOrderId(tradeNo);
                order.setOrderStatus(Order.PENDING_SHIPMENT);
                order.setPayStatus(Order.PAID);
                order.setCheckoutTime(gmtPayment);
                orderMapper.updateById(order);
                return "true";
            }
        }
        return "";
    }
}
